<template>
  <!-- 物料主数据表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="600px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <!-- 第一行 -->
      <!-- <div style="margin: 0 10px 20px 0; font-weight: bold; font-size: 16px">
        基本信息
      </div> -->
      <!-- <el-divider content-position="left" v-if="!props.isReadonly"
        ><span style="font-weight: bold; font-size: 16px"
          >基本信息</span
        ></el-divider
      > -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="存货编码" prop="materialCode">
            <span class="word">{{ formData.materialCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="materialName">
            <span class="word">{{ formData.materialName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table
        :data="formData.generates"
        style="width: 100%"
        :key="Math.random"
        :show-overflow-tooltip="false"
        max-height="560px"
        border
      >
        <el-table-column prop="elementName" label="元素符号" width="280" />
        <el-table-column
          label="成份值%"
          align="center"
          props="elementValue"
          min-width="280"
        >
          <template #default="{ $index, row }">
            <el-form-item
              :prop="'generates.' + $index + '.elementValue'"
              :rules="rules.elementValue"
              label-width="0"
            >
              <el-input
                v-model="row.elementValue"
                placeholder="请输入成份值"
                style="min-width: 160px"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useDictionary } from "@/utils/useTable";

defineOptions({
  name: "MDMMATERIALCONFIG",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  rulesValue: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);
watch(
  () => props.rulesValue,
  (newVal: boolean) => {}
);
let formData: any = reactive({
  id: "",
  materialCode: "",
  materialName: "",
  materialGroupId: "",
  materialTypeId: "",
  materialType: "",
  shortCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  srcCode: "",
  lcCkd: "",
  materialState: "",
  packageType: "",
  handlingUnitType: "",
  ownAssets: "",
  materialSpecification: "",
  unit: "",
  length: "",
  width: "",
  height: "",
  cubage: "",
  basalArea: "",
  volume: "",
  roughWeight: "",
  netWeight: "",
  enabled: 1,
  isConvert: 0,
  remarks: "",
  version: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
  figureNumber: "",
  materialQuality: "",
  generates: [],
});

const rules = reactive({
  elementValue: [
    { required: true, message: "请输入成分值", trigger: "blur" },
    {
      validator: validator,
      trigger: "blur",
    },
  ],
});

function validator(rule, value, callback: (a?: any) => {}) {
  // if (!value) {
  //   //先判断空可以过
  //   callback(new Error("请输入数值型数据，精度支持保留三位小数"));
  // } else {
  if (/^\d{1,8}(\.\d{0,3})?$/.test(value)) {
    //验证正整数和0的正则
    return true;
  } else {
    callback(new Error("请输入数值型数据，精度支持保留三位小数"));
  }
  // }
}

const materialGroup = ref("");
const materialGroupChange = (id: any) => {
  for (let i = 0; i < mdmmatgroup.value.length; i++) {
    if (mdmmatgroup.value[i].id == id) {
      materialGroup.value = mdmmatgroup.value[i].materialGroupName;
    }
  }
};

const plantListLable = ref("");
const plant = (code: any) => {
  for (let i = 0; i < plantList.value.length; i++) {
    if (plantList.value[i].organizationCode == code) {
      plantListLable.value = plantList.value[i].organizationName;
    }
  }
};

const formRef = ref(ElForm);

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        materialCode,
        materialName,
        materialGroupId,
        materialTypeId,
        materialType,
        shortCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        srcCode,
        lcCkd,
        materialState,
        packageType,
        handlingUnitType,
        ownAssets,
        materialSpecification,
        unit,
        isConvert,
        length,
        width,
        height,
        cubage,
        basalArea,
        volume,
        roughWeight,
        netWeight,
        enabled,
        remarks,
        version,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
        figureNumber,
        materialQuality,
        generates,
      } = newVal;
      Object.assign(formData, {
        id,
        materialCode,
        materialName,
        materialGroupId,
        materialTypeId,
        materialType,
        shortCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        srcCode,
        lcCkd,
        materialState,
        packageType,
        handlingUnitType,
        ownAssets,
        materialSpecification,
        unit,
        isConvert,
        length,
        width,
        height,
        cubage,
        basalArea,
        volume,
        roughWeight,
        netWeight,
        enabled,
        remarks,
        version,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
        figureNumber,
        materialQuality,
        generates,
      });
      if (formData.id) {
        getDetails(formData.id);
      }
      formData.packageType = String(formData.packageType);
      formData.lcCkd = String(formData.lcCkd);
      formData.materialType = String(formData.materialType);
      formData.unit = String(formData.unit);
      formData.materialState = String(formData.materialState);
      formData.handlingUnitType = String(formData.handlingUnitType);
      formData.ownAssets = String(formData.ownAssets);
      formData.enabled = Number(formData.enabled);
      materialGroupChange(formData.materialGroupId);
      plant(formData.plantCode);
      getMdmmatgroup();
    }
  }
);

async function getDetails(id: any) {
  const data = await request({
    url: `/mes/smtproductelement/getList/${id}`,
    method: "get",
  }).finally(() => {
    loading.value = false;
  });
  formData.generates = data.data;
}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  // formRef.value.clearValidate();
  formData.id = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.materialGroupId = "";
  formData.materialTypeId = "";
  formData.materialType = "";
  formData.shortCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.srcCode = "";
  formData.lcCkd = "";
  formData.materialState = "";
  formData.packageType = "";
  formData.handlingUnitType = "";
  formData.ownAssets = "";
  formData.materialSpecification = "";
  formData.unit = "";
  formData.isConvert = 0;
  formData.length = "";
  formData.width = "";
  formData.height = "";
  formData.cubage = "";
  formData.basalArea = "";
  formData.volume = "";
  formData.roughWeight = "";
  formData.netWeight = "";
  formData.enabled = 1;
  formData.remarks = "";
  formData.version = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.figureNumber = "";
  formData.materialQuality = "";
  formData.generates = [];
}
// 一开始展示基本数据
const activeName = ref("first");

const loading = ref(false);

/** 物料主数据保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      for (let i = 0; i < formData.generates.length; i++) {
        formData.generates[i].productId = formData.id;
        formData.generates[i].productCode = formData.materialCode;
        formData.generates[i].productName = formData.materialName;
      }
      loading.value = true;
      // const text = formData.id ? "编辑" : "新增";
      const text = "编辑";
      await request({
        url: "/mes/smtproductelement/saveBatch",
        method: "post",
        data: formData.generates,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
const plantList: any = ref([]);
const mdmmatgroup: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};

const getMdmmatgroup = async () => {
  if (formData.plantCode != "") {
    for (let i = 0; i < plantList.value.length; i++) {
      if (plantList.value[i].organizationCode == formData.plantCode) {
        formData.plantId = plantList.value[i].id;
      }
    }

    const res2 = await request({
      url: `/mdm/mdmmatgroup/getList`,
      method: "post",
      data: { plantId: formData.plantId },
    });

    mdmmatgroup.value = res2.data;
  } else {
    formData.materialGroupId = "";
    mdmmatgroup.value = [];
  }
};

// 输入框出发时
const changePlant = () => {
  getMdmmatgroup();
};
onMounted(() => {
  getPlantList();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style scoped lang="scss">
.right-input {
  :deep(.el-input__inner) {
    text-align: right;
    padding-right: 20px;
  }

  :deep(.el-input__inner::placeholder) {
    text-align: right;
  }

  :deep(.el-form-item__error) {
    right: 0px !important;
  }
}
.word {
  word-wrap: break-word;
  width: 200px; /* 设置容器宽度 */
}
</style>
